import * as vscode from 'vscode';
import * as fs from 'fs';
import workspace = vscode.workspace;
// import { sync } from 'glob';

const WND_FILE_DATA: string[] = [
	"module hg.game {",
	"\texport class <<ClassName>> extends WndBase {",
	"",
	"\t\tpublic static Ins: <<ClassName>>;",
	"\t\tprivate static _Ins = core.DclIns(<<ClassName>>);",
	"",
	"\t\tpublic OnCreateWindow() {",
	"\t\t\tsuper.OnCreateWindow();",
	"\t\t}",
	"",
	"\t\tpublic OnInit() {",
	"\t\t\tsuper.OnInit();",
	"\t\t}",
	"",
	"\t\tpublic OnHideWindow() {",
	"\t\t\tsuper.OnHideWindow();",
	"\t\t}",
	"",
	"\t\tpublic OnUpdateUI() {",
	"\t\t\tsuper.OnUpdateUI();",
	"\t\t}",
	"",
	"\t\tpublic openFor() {",
	"\t\t\tcore.UIMgr.Ins.OpenWindow(WND_ID.<<WndID>>);",
	"\t\t}",
	"",
	"",
	"\t}",
	"}",
]

export async function addIdDefAsync() {
	const workspaceFolders = workspace.workspaceFolders;
	if (!workspaceFolders) {
		vscode.window.showInformationMessage('workspace undefined');
		return;
	}
	//找到并读取IDDef枚举文件
	// src/src_base/base/WndIDDef.ts
	// const EnumPaths = sync(workspaceFolders[0].uri.fsPath + "/src/**/WndIDDef.ts");
	const EnumPaths = [
		workspaceFolders[0].uri.fsPath + '/src/base/WndIDDef.ts',
		workspaceFolders[0].uri.fsPath + '/src/src_base/base/WndIDDef.ts',
		workspaceFolders[0].uri.fsPath + '/src/src_ext/base/WndIDDef.ts'
	]

	if (!EnumPaths.length) {
		vscode.window.showInformationMessage('src目录下不存在WndIDDef.ts文件');
		return;
	}

	let EnumUri: vscode.Uri | undefined;
	for (let j = 0; j < EnumPaths.length; j++) {
		let Uri = vscode.Uri.file(EnumPaths[j]);
		if (!fs.existsSync(Uri.fsPath)) {
			continue;
		}
		const EnumDocument = await workspace.openTextDocument(EnumPaths[j]);
		if (EnumDocument.getText().includes("export const enum WND_ID {")) {
			EnumUri = vscode.Uri.file(EnumPaths[j]);
			break;
		}
	}

	if (!EnumUri) {
		vscode.window.showInformationMessage('未找到WndIDDef枚举');
		return;
	}

	const EnumDocument = await workspace.openTextDocument(EnumUri);
	const IDDefArr: string[] = [];
	let toInsertLine: vscode.TextLine | undefined;
	for (let index = 0; index < EnumDocument.lineCount; index++) {
		const line = EnumDocument.lineAt(index);
		const res = line.text.match(/(\S+),/);
		if (res && res[1]) {
			IDDefArr.push(res[1]);
		}
		if (line.text.search("WND_BLACK,") > 0) {
			toInsertLine = line;
		}
	}

	//读取WndIDDef文件

	const activeEditor = vscode.window.activeTextEditor;
	if (!activeEditor || !activeEditor.document.fileName.includes("WndIDDef")) {
		vscode.window.showInformationMessage("请在对应的WndIDDef文件中执行");
		return;
	}

	const document = activeEditor.document;
	const matchReg = new RegExp(/\s{4}core\.WND_INFO\[WND_ID\.(\S+)\] = <core\.WND_INFO_DATA>\{ cls: hg\.game\.(\S+), skin: "\S*".*\};/);
	const needAddID: string[] = [];
	const needAddClass: string[] = [];
	for (let index = 0; index < document.lineCount; index++) {
		const line = document.lineAt(index);
		const res = line.text.match(matchReg);
		if (res && !IDDefArr.includes(res[1])) {
			needAddID.push(res[1]);
			needAddClass.push(res[2]);
		}
	}

	//插入枚举到WndIDDef文件
	const IDEnumEditor = await vscode.window.showTextDocument(EnumDocument, { preserveFocus: false, preview: false, selection: toInsertLine?.range });
	await IDEnumEditor.edit(edit => {
		if (!toInsertLine) {
			vscode.window.showInformationMessage('WndIDDef 中的 WND_BLACK 枚举不存在');
			return;
		}
		for (let i = 0; i < needAddID.length; i++) {
			edit.insert(toInsertLine.rangeIncludingLineBreak.start, `\t\t${needAddID[i]},\n`);
		}
	});
	await vscode.commands.executeCommand('workbench.action.files.save');

	const shellDirReg = new RegExp(/src(\S*)\/base\/WndIDDef.ts/);
	const dir = activeEditor.document.uri.path.match(shellDirReg)?.[1];

	//创建窗口类文件
	const wsEdit = new vscode.WorkspaceEdit();
	for (let i = 0; i < needAddClass.length; i++) {
		const shellUri = vscode.Uri.joinPath(workspaceFolders[0].uri, "/src" + dir + "/shell/" + needAddClass[i] + ".ts");
		wsEdit.createFile(shellUri, { ignoreIfExists: true });
		await vscode.workspace.applyEdit(wsEdit);
	}

	//插入窗口类文件内容
	for (let i = 0; i < needAddClass.length; i++) {
		const shellUri = vscode.Uri.joinPath(workspaceFolders[0].uri, "/src" + dir + "/shell/" + needAddClass[i] + ".ts");
		fs.writeFileSync(shellUri.fsPath, WND_FILE_DATA.join("\n").replace(/<<WndID>>/g, needAddID[i]).replace(/<<ClassName>>/g, needAddClass[i]));
		vscode.window.showInformationMessage(needAddClass[i] + "创建完成");
	}
}
